package com.itboye.sunsun.buy.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import org.json.JSONObject;

import com.alipay.sdk.app.PayTask;
import com.itboye.sunsun.R;
import com.itboye.sunsun.alipay.PayDemoActivity;
import com.itboye.sunsun.alipay.PayResult;
import com.itboye.sunsun.alipay.SignUtils;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.OrderQueRenDingDan;
import com.itboye.sunsun.beans.PersonDataBean;
import com.itboye.sunsun.beans.WeChatBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.LoginedState;
import com.itboye.sunsun.login.ui.LoginActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.Debug;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.CodeErrorException;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsun.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class QueRenZhiFuActivity extends BaseActivity {

	private IWXAPI api;
	// 商户PID
	public static final String PARTNER = "2088122913686583";
	// 商户收款账号
	public static final String SELLER = "1580468651@qq.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMcu9yXiJ54oHnGE"
			+ "q05YO/zMJMwjYrvN6aIHi3hi+MkeqKWt8Cdq+51sO3rr1TKyaA5pFTeit/8th+hI"
			+ "c6HSRNJG6dCTwzTAtAJIljlA8NWFL3Pmd8iA6H/rR+Mf2LXTGBTPuB0X3Xn2sMZE"
			+ "1BmwwO6A8buJRLuP1gtjfr0ZpFLlAgMBAAECgYA5lOg5+XE+lZaHdrUXRwbAhDu3"
			+ "EBvA8zwxbUDyopoNemGC1A/zNUhcMCfZ10ehClZupA5QMShECuOZUSishV8DcFzo"
			+ "OCYb0VchTRyIQmOZsFKv5sWAjPnLcBMYMVzVQt5XcYwvPBBbX3VETQrT/tYxz9Oh"
			+ "J55ieswAXsQmpCQkGQJBAO7Hl5SyeMJQNuB8EEvYHzuWLLp5BzBKfB12ASpeSeXB"
			+ "Y0jFeScSb+ueO+7ZrI/xcABQONiFGlRIiaQty29CBYsCQQDVjFa1a4k5BPwumNSu"
			+ "/2qYBI+anPa8OQwFZsFVpLS7+Il6k2WJ1idd8mlxeTyY50RD3G/dXyb1lKcHws4L"
			+ "M3dPAkEApEKxyB0ubZ344lz2aPZ4JemdQ3pWs6XJ1AqFqrvKYj+zKTCPs40/aPsl"
			+ "h54+05bn0Y9eS7Tk8+4iocrPE+57GQJAVTYdt2DErdr+Yf2cCIRk3Wocf16Y2fyN"
			+ "fm5FQU5qzALdoOrF/p1Ushkz2BK/imfmBooknRoF6sK5b9Bc9X1A4wJBANA41dk4"
			+ "y7vXK2gk+jbweh4A+sRJples1JDIPX4wHKIU0QKqk6xD4TgPBE8Aq9zpiTlVc4yd" + "/UsxwH35RviPhAM=";
	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
	private static final int SDK_PAY_FLAG = 1;

	private View alipayview;
	private View wechatpayview;
	private RelativeLayout alipayrela;
	private RelativeLayout wechatpayrela;

	private boolean aliselect = true;
	private boolean wechatselect = false;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(QueRenZhiFuActivity.this, "支付成功", Toast.LENGTH_LONG).show();
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(QueRenZhiFuActivity.this, "支付结果确认中", Toast.LENGTH_LONG).show();

					} else if (TextUtils.equals(resultStatus, "4000")) {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(QueRenZhiFuActivity.this, "支付失败，请检查安装支付宝", Toast.LENGTH_LONG).show();

					}else if (TextUtils.equals(resultStatus, "6001")) {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(QueRenZhiFuActivity.this, "支付取消", Toast.LENGTH_LONG).show();

					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.pay_main);
		api = WXAPIFactory.createWXAPI(this, "wxa30658c4f4f6bbf4");
		api.registerApp("wxa30658c4f4f6bbf4");
		setContentView(R.layout.activity_queren_zhifu);
		
		
		IntentFilter filter=new IntentFilter(WXPayEntryActivity.FinishQueRen);
		registerReceiver(mBroadCast, filter);

		findViewById(R.id.alipayrela).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(App.ctx, "hah"+aliselect, 0).show();
				aliselect = !aliselect;
				if (aliselect) {
					wechatselect = false;
					alipayview
							.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.ic_shop_car_selected));
					wechatpayview.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.un_select));
				} else {
					wechatselect = true;
					alipayview.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.un_select));
					wechatpayview
							.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.ic_shop_car_selected));
				}

			}
		});
		findViewById(R.id.wechatpayrela).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(App.ctx, "hah"+wechatselect, 0).show();
				wechatselect = !wechatselect;
				if (wechatselect) {
					aliselect = false;
					wechatpayview
							.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.ic_shop_car_selected));
					alipayview.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.un_select));
				} else {
					aliselect = true;
					wechatpayview.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.un_select));
					alipayview
							.setBackgroundDrawable(App.ctx.getResources().getDrawable(R.drawable.ic_shop_car_selected));
				}

			}
		});

		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		findViewById(R.id.pay).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (aliselect) {
					pay(v);
				} else {
					wechatpay();
				}
			}

		});

		OrderQueRenDingDan order = (OrderQueRenDingDan) getIntent().getSerializableExtra("what");
		((TextView) findViewById(R.id.price)).setText(order.getTotalPrice());

	}

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */

	private void wechatpay() {

		OrderQueRenDingDan order = (OrderQueRenDingDan) getIntent().getSerializableExtra("what");
		String code = order.getCode();
		String desc=order.getDesc();
		String price=order.getTotalPrice();
		
//		//如果是从积分商城跳过来的
//		Intent intent=getIntent();
//		String code1=intent.getStringExtra("ordercode");
//		
//		if(code1.equals(""))
//		{
//			code=code;
//		}else
//		{
//			code=code1;
//		}

		MyJsonRequest<WeChatBean> request = new MyJsonRequest.Builder<WeChatBean>().apiVer("100")
				.typeKey("BY_Wxpay_preOrder")
				.param("code", code)
				.param("desc", desc)
				.param("total_price", price)

				.requestListener(new XRequestListener<WeChatBean>() {

					@Override
					public void onResponse(WeChatBean response) {
						PayReq req = new PayReq();
						req.appId = response.getAppid();
						req.partnerId = response.getPartnerid();
						req.prepayId = response.getPrepayid();
						req.nonceStr = response.getNoncestr();
						req.timeStamp = response.getTimestamp();
						req.packageValue = "Sign=WXPay";
						req.sign = response.getSign();
						boolean is=api.sendReq(req);
						if(is){
							
						}else{
							Toast.makeText(App.ctx, "调起微信支付失败", 0).show();
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
					//	Toast.makeText(App.ctx, "haha", 0).show();
						if (exception instanceof CodeErrorException) {
							Toast.makeText(App.ctx, msg, 0).show();
						} else {
							Toast.makeText(App.ctx, exception.toString(), 0).show();
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	public void pay(View v) {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							finish();
						}
					}).show();
			return;
		}
		OrderQueRenDingDan order = (OrderQueRenDingDan) getIntent().getSerializableExtra("what");

		// String orderInfo = getOrderInfo(order.getName(), order.getDesc(),
		// order.getTotalPrice());
		String orderInfo;
		if (Debug.isDebug) {
			orderInfo = getOrderInfo(order.getName(), order.getDesc(), "0.01");
		} else {
			orderInfo = getOrderInfo(order.getName(), order.getDesc(), order.getTotalPrice());
		}
		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(QueRenZhiFuActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
	// public void h5Pay(View v) {
	// Intent intent = new Intent(this, H5PayDemoActivity.class);
	// Bundle extras = new Bundle();
	// /**
	// * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
	// * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
	// * 商户可以根据自己的需求来实现
	// */
	// String url = "http://m.meituan.com";
	// // url可以是一号店或者美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
	// extras.putString("url", url);
	// intent.putExtras(extras);
	// startActivity(intent);
	//
	// }

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + NetPublicConstant.URL+"/AlipayApp/return_url" + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		// SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
		// Locale.getDefault());
		// Date date = new Date();
		// String key = format.format(date);
		//
		// Random r = new Random();
		// key = key + r.nextInt();
		// key = key.substring(0, 15);
		OrderQueRenDingDan order = (OrderQueRenDingDan) getIntent().getSerializableExtra("what");
		return order.getCode();
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}
	
	BroadcastReceiver mBroadCast=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			QueRenZhiFuActivity.this.finish();
			
		}
	};
	protected void onDestroy() 
	{
		super.onDestroy();
		unregisterReceiver(mBroadCast);
	};

}
